package com.xhl.demo.someFilter.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述
 * @author 徐宏亮
 * @date 2019/3/2 11:55
 */
//@Component
public class TimeInterceptor implements HandlerInterceptor {

    /**
     * 功能描述 控制器方法被调用之前
     * @author 徐宏亮
     * @date 2019/3/2 11:56
     * @param request
     * @param response
     * @param handler
     * @return boolean
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod)handler).getMethod().getName());
        request.setAttribute("startTime", System.currentTimeMillis());
        return true;
    }

    //控制器方法被处理之后调用，如果控制器抛出异常，不会被调用
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
        System.out.println("time filter 耗时:" + (System.currentTimeMillis() - (long)request.getAttribute("startTime")));
        System.out.println("ex is" + handler);
    }

    /**
     * 功能描述 无论控制器异常还是正常运行后，都会被调用
     * @author 徐宏亮
     * @date 2019/3/2 11:57
     * @param request
     * @param response
     * @param handler
     * @param ex 控制器有异常时，这里会有值
     *           注意：这里的异常可能会被别的异常处理器处理，处理之后这里也是没有值的
     * @return void
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
        System.out.println("time filter 耗时:" + (System.currentTimeMillis() - (long)request.getAttribute("startTime")));
        System.out.println("ex is " + ex);
    }
}
